package com.alex.utils.search;

import java.io.IOException;
import java.util.Iterator;
import java.util.NoSuchElementException;

import com.alex.utils.search.SearchResults.Document;

public abstract class Searcher {

	public abstract SearchResults search(String query, int pageNumber) throws SearchException, IOException;

	public SearchResultsIterator search(String query) {
		return new SearchResultsIteratorImpl(query);
	}

	class SearchResultsIteratorImpl implements SearchResultsIterator {

		private int page = 0;

		private SearchResults searchResults;

		private Iterator<Document> iterator;

		private String query;

		public SearchResultsIteratorImpl(String query) {
			this.query = query;
		}

		@Override
		public boolean hasNext() throws SearchException, IOException {
			if (iterator == null || !iterator.hasNext()) {
				if (page >= 10 || searchResults != null && !searchResults.hasNextPage()) {
					return false;
				}

				searchResults = search(query, page++);
				if (!searchResults.getDocuments().isEmpty()) {
					iterator = searchResults.getDocuments().iterator();
				} else {
					return false;
				}
			}
			return true;
		}

		@Override
		public Document next() throws SearchException {
			if (iterator == null) {
				throw new NoSuchElementException();
			}
			return iterator.next();
		}
	}

}
